package baidumodel.util;

import baidumodel.entity.CodeEnum;
import baidumodel.entity.chat.ResponseCode;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;

/**
 *
 * @Author wuchenxi
 * @Date 2023-07-23 18:43:28
 */
public class HttpUtil {

    public static String get(String url) {
        long startTime = System.currentTimeMillis();
        String s = cn.hutool.http.HttpUtil.get(url);
        System.out.printf("请求接口：%s 耗时:%sms \n", url, System.currentTimeMillis() - startTime);
        printCodeMsg(s, url);
        return s;
    }

    public static String post(String url, String body) {
        long startTime = System.currentTimeMillis();
        String s = cn.hutool.http.HttpUtil.post(url, body);
        System.out.printf("请求接口：%s， 耗时:%sms \n", url, System.currentTimeMillis() - startTime);
        printCodeMsg(s, url);
        return s;
    }

    private static void printCodeMsg(String s, String url) {
        try {
            ResponseCode responseCode = JSONUtil.toBean(s, ResponseCode.class);
            String errorCode = responseCode.getError_code();
            if (!NumberUtil.isNumber(errorCode)) {
                return;
            }
            CodeEnum codeEnum = CodeEnum.getByCode(NumberUtil.parseInt(errorCode));
            if (codeEnum != null) {
                System.out.printf("请求接口：%s 错误码信息：code=%d，errMsg=%s，desc=%s \n", url, codeEnum.getCode(), codeEnum.getErrMsg(), codeEnum.getDesc());
            }
        } catch (Exception e) {

        }
    }
}
